<?php

namespace App\Http\Controllers\Manage;

use App\Http\Model\Manage\AdminDepartmentModel;
use App\Http\Model\Manage\AdminModel;
use App\Http\Model\Manage\AdminRoleModel;
use Illuminate\Contracts\View\View;
use Illuminate\Http\Request;


class AdminController extends BasicController
{

    /**
     * 重置管理员密码
     * @param Request $request
     * @return array|string
     */
    public function passwordInfoAction(Request $request, string $code): array|string
    {
        $has = AdminModel::where([
            ['code', '=', $code],
        ])->first();
        if (!$has)
        {
            return errorReturn("用户不存在");
        }
        $loginInfo = $this->getLoginInfo($request);
        $admin = $loginInfo['admin'];
        $role = $loginInfo['role'];
        if ($has->pCode != $admin->code)
        {
            return errorReturn("无权限操作该用户");
        }
        $password = md5(md5("123456789"."123456789")."asdfghjkl");
        $safety = substr($password,3,8);
        $delete = (new AdminModel)->updateInfo(dataToWhere([
            "code"=>$code,
            "version"=>$has->version,
            "pCode"=>$admin->code
        ]), [
            "lta003"=>$safety,
            "lta002"=>$password,
            "uLtaCode"=>$admin->code,
            "uLtarCode"=>$role->code,
        ]);
        if ($delete)
        {
            return successReturn("操作成功");
        }
        return errorReturn("操作失败");
    }

    /**
     * 删除管理员
     * @param Request $request
     * @param string $code
     * @return array|string
     */
    public function deleteInfoAction(Request $request, string $code): array|string
    {
        $has = AdminModel::where([
            ['code', '=', $code],
        ])->first();
        if (!$has)
        {
            return errorReturn("用户不存在");
        }
        $loginInfo = $this->getLoginInfo($request);
        $admin = $loginInfo['admin'];
        $role = $loginInfo['role'];
        $underAdminCode = $this->getAllAdminUnderCode($admin->code);
        if (!in_array($has->code,$underAdminCode))
        {
            return errorReturn("无权限操作该用户");
        }
        $underThisAdminCode = $this->getAllAdminUnderCode($has->code);
        $delete = (new AdminModel)->deleteInfo([], [
            "uLtaCode"=>$admin->code,
            "uLtarCode"=>$role->code,
        ], "code", $underThisAdminCode);
        if ($delete)
        {
            return successReturn("操作成功");
        }
        return errorReturn("操作失败");
    }

    /**
     * 修改管理员状态
     * @param Request $request
     * @param string $code
     * @return array|string
     */
    public function statusInfoAction(Request $request, string $code): array|string
    {
        $has = AdminModel::where([
            ['code', '=', $code],
        ])->first();
        if (!$has)
        {
            return errorReturn("用户不存在");
        }
        $loginInfo = $this->getLoginInfo($request);
        $admin = $loginInfo['admin'];
        $role = $loginInfo['role'];
        $underAdminCode = $this->getAllAdminUnderCode($admin->code);
        if (!in_array($has->code,$underAdminCode))
        {
            return errorReturn("无权限操作该用户");
        }
        $update = (new AdminModel)->updateInfo(dataToWhere([
            "code"=>$code,
            "version"=>$has->version,
        ]), [
            "status"=>$has->status == 1 ? 0: 1,
            "uLtaCode"=>$admin->code,
            "uLtarCode"=>$role->code,
        ]);
        if ($update)
        {
            return successReturn("操作成功");
        }
        return errorReturn("操作失败");
    }

    /**
     * 添加管理员
     * @param Request $request
     * @return View
     */
    public function addInfoAction(Request $request): array|string
    {
        $data = $request->all();
        $loginInfo = $this->getLoginInfo($request);
        $admin = $loginInfo['admin'];
        $role = $loginInfo['role'];
        $lta001 = $data["lta001"];
        $has = AdminModel::where([
            ['lta001', '=', $lta001],
        ])->first();
        if ($has)
        {
            return errorReturn("用户已存在");
        }
        $lta002 = md5(md5($data["lta002"]."123456789")."asdfghjkl");
        $lta003 = substr($lta002,3,8);
        $underDepartment = $this->getAllDepartmentUnderCode($admin->ltadCode);
        if (!in_array($data["ltadCode"],$underDepartment))
        {
            return errorReturn("无权限操作该部门科室");
        }
        $adminId = (new AdminModel)->createInfo([
            "lta001"=>$lta001,
            "lta002"=>$lta002,
            "lta003"=>$lta003,
            "lta004"=>$data["lta004"],
            "lta005"=>$data["lta005"],
            "ltarCodes"=>$data["ltarCodes"],
            "ltadCode"=>$data["ltadCode"],
            "pCode"=>$data["pCode"],
            "cLtaCode"=>$admin->code,
            "uLtaCode"=>$admin->code,
            "uLtarCode"=>$role->code,
        ]);
        if ($adminId > 0 )
        {
            return successReturn("添加成功");
        }
        else
        {
            return errorReturn("添加失败");
        }

    }

    /**
     * 修改管理员信息
     * @param Request $request
     * @return View
     */
    public function editInfoAction(Request $request): array|string
    {
        $data = $request->all();
        $has = AdminModel::where([
            ['code', '=', $data["code"]],
        ])->first();
        if (!$has)
        {
            return errorReturn("用户不存在");
        }
        $loginInfo = $this->getLoginInfo($request);
        $admin = $loginInfo['admin'];
        $role = $loginInfo['role'];
        $underAdminCode = $this->getAllAdminUnderCode($admin->code);
        if (!in_array($has->code,$underAdminCode))
        {
            return errorReturn("无权限操作该用户");
        }
        $underThisAdminCode = $this->getAllAdminUnderCode($has->code);
        if (in_array($data["pCode"],$underThisAdminCode))
        {
            return errorReturn("不可以将上级管理员设置为其下级管理员");
        }
        $underDepartment = $this->getAllDepartmentUnderCode($admin->ltadCode);
        if (!in_array($data["ltadCode"],$underDepartment))
        {
            return errorReturn("无权限操作该部门科室");
        }
        $update = (new AdminModel)->updateInfo(dataToWhere([
            "code"=>$has->code,
            "version"=>$has->version
        ]), [
            "lta004"=>$data["lta004"],
            "lta005"=>$data["lta005"],
            "pCode"=>$data["pCode"],
            "ltarCodes"=>$data["ltarCodes"],
            "ltadCode"=>$data["ltadCode"],
            "uLtaCode"=>$admin->code,
            "uLtarCode"=>$role->code,
        ]);
        if ($update)
        {
            return successReturn("操作成功");
        }
        return errorReturn("操作失败");
    }

    /**
     * 管理员列表页面
     * @param Request $request
     * @return View
     */
    public function pageTableView(Request $request): View
    {
        $loginInfo = $this->getLoginInfo($request);
        $role = $loginInfo['role'];
        $underRoleCode = $this->getAllRoleUnderCode($role->code, true);
        $roleList = AdminRoleModel::whereIn("code", $underRoleCode)->where([
            [ 'deleted', "=", 0],
        ])->orderBy('id','asc')->get()->toarray();
        $admin = $loginInfo["admin"];
        $underAdminCode = $this->getAllAdminUnderCode($admin->code,  true);
        $underAdmin = AdminModel::whereIn("code", $underAdminCode)->where([
            [ 'deleted', "=", 0],
        ])->orderBy('id','asc')->get()->toarray();
        $underDepartment = $this->getAllDepartmentUnderCode($admin->ltadCode, true);
        $underDepartment = AdminDepartmentModel::whereIn("code", $underDepartment)->where([
            [ 'deleted', "=", 0],
        ])->orderBy('id','asc')->get()->toarray();
        return view($this->viewPath."system.admin_table", ["admin"=>$admin, "role"=>$role, "roleList" => $roleList, "adminList"=>$underAdmin, "departmentList"=>$underDepartment]);
    }

    /**
     * 管理员列表数据
     * @param Request $request 请求参数 page 当前页码 limit 每页数量
     * @return array|string
     */
    public function pageTableData(Request $request): array|string
    {
        $loginInfo = $this->getLoginInfo($request);
        $admin = $loginInfo["admin"];
        $underAdminCode = $this->getAllAdminUnderCode($admin->code);
        $underAdminCode = array_diff($underAdminCode, [$admin->code]);
        $underAdmin = AdminModel::whereIn("code", $underAdminCode)->where([
            [ 'deleted', "=", 0],
        ])->orderBy('id','asc')->get()->toarray();
        $underAdmin = dataToTree($underAdmin, "code", "pCode");
        return successReturn("加载成功", $underAdmin);
    }

    /**
     * 管理员修改自己信息的页面
     * @param Request $request
     * @return View
     */
    public function changeOwnInfoView(Request $request): View
    {
        $loginInfo = $this->getLoginInfo($request);
        return view($this->viewPath.'admin.change.info', [
            'admin' => $loginInfo['admin'],
            'role' => $loginInfo['role'],
        ]);
    }

    public function changeOwnInfoAction(Request $request)
    {

    }


    /**
     * 自己修改自己的密码
     * @return View
     */
    public function changeOwnPwdView(): View
    {
        return view($this->viewPath.'admin.change.password');
    }

    /**
     * 自己修改自己密码修改
     * <p>
     *     1. 获取修改参数
     *     2. 验证两次新密码是否相同
     *     3. 验证原始密码是否正确
     *     4. 修改密码
     *     5. 修改成功 删除session 重新登录
     * </p>
     * @param Request $request
     * @return array|string
     */
    public function changeOwnPwdAction(Request $request): array|string
    {
        $data = $request->all();
        if ($data["newPassword"] != $data["reNewPassword"]) {
            return errorReturn("两次新密码不一致");
        }
        $loginInfo = $this->getLoginInfo($request);
        $admin = $loginInfo['admin'];
        $role = $loginInfo['role'];
        $password = md5(md5($data["oldPassword"]."123456789")."asdfghjkl");
        $safety = substr($password,3,8);
        if ($admin->lta003 != $safety || $admin->lta002 != $password) {
            return errorReturn("原始密码错误");
        }
        $newPassword = md5(md5($data["newPassword"]."123456789")."asdfghjkl");
        $newSafety = substr($newPassword,3,8);
        $update = (new AdminModel)->updateInfo(dataToWhere([
            "code"=>$admin->code,
            "lta003"=>$safety,
            "lta002"=>$password
        ]), [
            "lta003"=>$newSafety,
            "lta002"=>$newPassword,
            "uLtaCode"=>$admin->code,
            "uLtarCode"=>$role->code,
        ]);
        if ($update) {
            $request->session()->flush();
            return successReturn("修改成功");
        } else {
            return errorReturn("修改失败");
        }
    }
}
